package cn.cqie.attendance.common.controller;

import cn.cqie.attendance.common.pojo.User;
import cn.cqie.attendance.common.service.LoginService;
import cn.cqie.attendance.common.util.JwtUtil;
import cn.cqie.attendance.common.util.LocalJwt;
import cn.cqie.attendance.common.util.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
@Api(tags = "登陆控制器")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/loginSub")
    @CrossOrigin(allowCredentials = "true")
    @ApiOperation(value = "登陆判断")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名(189000421)", required = true),
            @ApiImplicitParam(name = "password", value = "密码(111)", required = true),
            @ApiImplicitParam(name = "role", value = "角色(student)", required = true),
            @ApiImplicitParam(name = "tryCode", value = "填写的验证码", required = true)})
    public Page loginSub(String username, String password, String role,
                         String tryCode, String UUID) {
        System.out.println("请求的UUID为: " + UUID);
        String rightCode = LocalJwt.getCode(UUID);
        System.out.println("尝试比对验证码: 尝试的验证码为->" + tryCode + ", 正确验证码为->" + rightCode);
        if (StringUtils.isEmpty(tryCode)) {
            return new Page(999, "验证码不能为空");
        }
        if (rightCode == null) {
            return new Page(999, "验证码失效");
        }
        if (!tryCode.equals(rightCode)) {
            return new Page(999, "验证码错误");
        }
        LocalJwt.removeCode(UUID);
        if (username != null && password != null && role != null) {

            User user = null;
            if ("student".equals(role)) {
                user = loginService.queryStudent(username);
            } else {
                user = loginService.queryTeacher(username);
            }

            if (user == null) {
                return Page.INFOERROR;
            } else if (user.getStatus() == 0) {
                return Page.FAIL;
            } else if ("admin".equals(role) && user.getRole() == 0) {
                return Page.INFOERROR;
            } else if ("teacher".equals(role) && user.getRole() == 1) {
                return Page.INFOERROR;
            }

            if (user.getLoginTimes() != 0) {
                SimpleHash simpleHash = new SimpleHash("MD5", password,
                        user.getId() + "team7", 2);

                if (!simpleHash.toHex().equals(user.getPassword())) {
                    return Page.INFOERROR;
                }
            } else if (!user.getPassword().equals(password)) {
                return Page.INFOERROR;
            }

            // 生成token
            String token = JwtUtil.sign(username);
            LocalJwt.setSignUser(token, user);
            // 测试先关闭，上线后开启
//            loginService.loginOnce(user.getId(), role);
            return new Page(200, "success", new User(token, user.getLoginTimes()));
        }
        return new Page(999, "用户名密码不能为空");
    }

    @GetMapping("/logout")
    @ApiOperation(value = "登出")
    public Page logout() {
        LocalJwt.removeCurrentUser(request);
        return Page.SUCCESS;
    }

    @PostMapping("/changePassword")
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({@ApiImplicitParam(name = "oldPassword", value = "原密码", required = true),
            @ApiImplicitParam(name = "newPassword", value = "新密码", required = true)})
    public Page changePassword(String oldPassword, String newPassword) {
        System.out.println("新密码为: " + newPassword);
        System.out.println("旧密码为: " + oldPassword);
        if (newPassword.length() < 6 || newPassword.length() > 16) {
            return new Page(999, "密码长度必须在6~16位");
        }
        User user = LocalJwt.getCurrentUser(request);
        String role = Objects.requireNonNull(user).getTag();
        SimpleHash simpleHash = new SimpleHash("MD5", oldPassword,
                user.getId() + "team7", 2);
        if (!simpleHash.toHex().equals(user.getPassword())) {
            return Page.INFOERROR;
        }
        newPassword = new SimpleHash("MD5", newPassword,
                user.getId() + "team7", 2).toHex();
        int result = loginService.changePassword(user.getId(), newPassword, role);
        if (result == 0) {
            return Page.EXCEPTION;
        }
        user.setPassword(newPassword);
        LocalJwt.setCurrentUser(request, user);
        return Page.SUCCESS;
    }
}
